<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import { userStore } from '../store/index.js'
import {Plus} from "@element-plus/icons-vue";
import UploadHeader from "./UploadHeader.vue";
import {useRouter} from "vue-router";
const router = useRouter();
const userItemStore = userStore()

const smallAvatarUrl = ref('');

const user = localStorage.getItem('user')

const userDetail = ref({})

const initializeUser = () => {
  if (user) {
    userDetail.value = JSON.parse(user)
    console.log(userDetail.value)
  }
}

const setAvatarUrls = () => {
  smallAvatarUrl.value = userItemStore.user.avatarUrl
}
const handleBellClick=()=>{
  router.push('/todo')
}


const avatarDialogVisible = ref(false);
const showAvatar = () => {
  avatarDialogVisible.value = true;
}

//===============================退出====================================
const logout = () => {
  ElMessageBox.confirm(
      `您确定要退出吗？`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
  axios.get('http://e2d8sy.natappfree.cc/user/logout')
      .then(() => {
        //删除本地存储
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        //清空通知标记记录
        localStorage.removeItem('FaultMana');
        localStorage.removeItem('FaultTrea');
        localStorage.removeItem('RiskMana');
        localStorage.removeItem('RiskTrea');
        //提示信息
        userItemStore.updateUser(null);
        userItemStore.updateLoginStatus(false);
        ElMessage.success('退出成功');
        router.push('/login');
      })
          .catch(error => {
            console.error(error);
          })
      })
      .catch(() => {})
}
//===================================修改密码==================================================
const visible4Edit = ref(false);
const user4Edit = ref({
  oldPassword: '',
  newPassword: '',
  checkPass: '',
});
const form = ref(null);
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== user4Edit.value.newPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入新密码'));
  } else {
    // 如果确认密码字段不为空，则验证是否匹配
    if (user4Edit.value.checkPass !== '') {
      form.value.validateField('checkPass', () => null);
    }
    callback();
  }
};

const rules=ref({
  oldPass: [
    {required: true, message: '请输入旧密码', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {validator: validatePass}
  ],
  checkPass: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {validator: validatePass2}
  ]
})

const showPassword = () => {
  visible4Edit.value = true;
  user4Edit.value = {
    oldPassword: '',
    newPassword: '',
    checkPass: '',
  };
}

const editUser = () => {
  form.value.validate((valid) => {
    if (valid) {
      axios.post('/user/changePassword', user4Edit.value)
          .then(() => {
            ElMessage.success('密码修改成功');
            visible4Edit.value = false;
            // 清除表单数据
            user4Edit.value = {
              oldPassword: '',
              newPassword: '',
              checkPass: ''
            };
            form.value.resetFields(); // 重置表单验证状态
          })
          .catch(error => {
            ElMessage.error(error.response.data || '密码修改失败，请重试');
          });
    } else {
      ElMessage.error('表单验证失败，请检查输入');
      return false;
    }
  });
};




onMounted(() => {
  setAvatarUrls();
  initializeUser();
})

</script>

<template>


      <el-row>
        <el-col :span="10" :offset="6" class="title">充电桩后台管理系统</el-col>
        <el-col :span="5" class="user" >

          <img v-if="smallAvatarUrl" :src="smallAvatarUrl" id="smallAvatar" title="点击更换头像" @click="showAvatar" />
          <img  v-else src="../assets/head-picture.jpg" id="smallAvatar" title="点击更换头像" @click="showAvatar" />
          <!-- 使用 el-tooltip 包裹需要提示的文本 -->
          <el-tooltip effect="light" placement="bottom" :disabled="!userItemStore.user">
            <template #content>
              <p>姓名: {{ userDetail.name }}</p>
              <p>职务: {{ userDetail.roleName }}</p>
              <p>本次登录地址: {{ userDetail.nowLog.ipMap }}(ip:{{userDetail.nowLog.ipAddress}})</p>
              <p>上次登录时间: {{ userDetail.lastLog.createdAt }}</p>
              <p>上次登录地址: {{ userDetail.lastLog.ipMap }}(ip:{{userDetail.lastLog.ipAddress}})</p>
              <p>
                <el-button type="text" @click="showPassword" style="margin-left: 20px">修改密码</el-button>
              </p>
            </template>
            <span>{{ userItemStore.user?.account }}, 欢迎你</span>
          </el-tooltip>



          <el-button type="text" @click="logout"  style="margin-left: 20px">退出</el-button>
        </el-col>
        <!-- 图标按钮 -->
        <el-col :span="2" class="bell-icon-col">
          <el-icon class="bell-icon" @click="handleBellClick"><Bell /></el-icon>
        </el-col>
      </el-row>

  <el-dialog v-model="avatarDialogVisible" title="选择头像" width="400" center>

<upload-header v-model:smallAvatarUrl="smallAvatarUrl" />

  </el-dialog>

  <!-- ========================================修改密码弹窗====================================================================== -->
  <el-dialog v-model="visible4Edit" title="修改密码" width="400">
    <el-form :model="user4Edit" :rules="rules" ref="form">
      <el-form-item label="原密码" label-width="130" prop="oldPass">
        <el-input v-model="user4Edit.oldPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" label-width="130" prop="password">
        <el-input
            v-model="user4Edit.newPassword"
            autocomplete="off"
            @input="() => form.value?.clearValidate('password')"
        />
      </el-form-item>
      <el-form-item label="再次输入新密码" label-width="130" prop="checkPass">
        <el-input
            v-model="user4Edit.checkPass"
            autocomplete="off"
            @input="() => form.value?.clearValidate('checkPass')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible4Edit = false">取消</el-button>
        <el-button type="primary" @click="editUser()">确认</el-button>
      </div>
    </template>
  </el-dialog>


</template>






<style scoped>
.title {
  color: rgba(252, 248, 248, 0.99);
  text-align: center;
  font-weight: bolder;
  font-size: 32px;
  line-height: 40px !important;
}

.user {
  line-height: 50px !important;
}

#smallAvatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  vertical-align: middle;

}
.bell-icon-col {
  /* 设置垂直居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.bell-icon {
  font-size: 24px; /* 设置图标大小 */
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}
</style>